package com.shuo.dsa.leetcode;

import java.util.Stack;

/**
 * 算式求值
 *      思路: 遍历String[]如果是数则直接丢到stack, 如果是运算符则pop两个数并进行计算再把结果push回stack,
 *      遍历完成后直接pop返回即可
 *
 * Evaluate the value of an arithmetic expression in Reverse Polish Notation.
 * Valid operators are+,-,*,/. Each operand may be an integer or another expression.
 * Some examples:
 * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
 * ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
 */
public class CalcStrFormula {

    public static void main(String[] args) {
        String[] q = new String[]{"2", "1", "+", "3", "*"};
        System.out.println(evalRPN(q));
    }

    public static int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();
        for (String token : tokens) {
            if ("+".equals(token)) {
                String num1 = stack.pop();
                String num2 = stack.pop();
                stack.push(Integer.toString(Integer.parseInt(num2) + Integer.parseInt(num1)));
            } else if ("-".equals(token)) {
                String num1 = stack.pop();
                String num2 = stack.pop();
                stack.push(Integer.toString(Integer.parseInt(num2) - Integer.parseInt(num1)));
            } else if ("*".equals(token)) {
                String num1 = stack.pop();
                String num2 = stack.pop();
                stack.push(Integer.toString(Integer.parseInt(num2) * Integer.parseInt(num1)));
            } else if ("/".equals(token)) {
                String num1 = stack.pop();
                String num2 = stack.pop();
                stack.push(Integer.toString(Integer.parseInt(num2) / Integer.parseInt(num1)));
            } else {
                stack.push(token);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}

